<template>
  <div>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入关键字" clearable v-model="name" @clear="searchTeam">
            <el-button slot="append" icon="el-icon-search" @click="searchTeam"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">新增信息</el-button>
        </el-col>
      </el-row>
      <el-table :data="teamList" border stripe>
        <el-table-column label="ID" prop="id" :width="50"></el-table-column>
        <el-table-column label="成员昵称" prop="managerName" :width="120"></el-table-column>
        <el-table-column label="头像" :width="130">
          <template v-slot="scope">
            <el-image
                style="width: 100px; height: 100px"
                :src="'https://woniu-adopt.oss-cn-hangzhou.aliyuncs.com/adoptImages/'+scope.row.pic"
                fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="团队成分" prop="typeName" :width="150"></el-table-column>
        <el-table-column label="个人介绍" prop="introduce" :width="500"></el-table-column>
        <el-table-column label="个人寄语" prop="message"></el-table-column>
        <el-table-column label="角色">
          <template v-slot="scope">
            {{ getRoleNames(scope.row.roleList) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" :width="130">
          <template v-slot="scope">
            <el-button type="warning" size="small" icon="el-icon-edit" @click="showEditDialog(scope.row)"
                       circle></el-button>
            <el-button type="danger" size="small" icon="el-icon-delete"
                       @click="removeUserById(scope.row.id)" circle></el-button>
          </template>
        </el-table-column>

      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[3, 6 , 12, 24]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </el-card>

    <!--添加团队成员信息-->
    <el-dialog title="添加团队成员信息" :visible.sync="addDialogVisible" width="50%"  :close-on-click-modal="false" @close="addTeamFormClose">
      <el-form
          :model="addTeamForm"
          :rules="addTeamFormRules"
          ref="addTeamFormRef"
          label-width="100px"
          class="demo-ruleForm"
      >
        <!--从没有填写个人团队信息的管理员列表中选择，不可多选
        需要先排除已有项-->
        <el-form-item label="团队成员" prop="mid">
          <el-select v-model="addTeamForm.mid" placeholder="请选择团队成员" @change="showTypeName(addTeamForm.mid)">
            <el-option :label="item.name" :value="item.id" v-for="item in managerList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="团队成分" prop="typeName">
          <el-input v-model="addTeamForm.typeName" disabled></el-input>
        </el-form-item>
        <el-form-item label="展示头像" prop="pic">
          <input type="file" @change="uploadPic"/>
          <img :src="showImg" alt="" :style="imgStyle"/>
        </el-form-item>
        <el-form-item label="简介" prop="introduce">
          <el-input v-model="addTeamForm.introduce"></el-input>
        </el-form-item>
        <el-form-item label="个人寄语" prop="message">
          <el-input v-model="addTeamForm.message"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addTeam">确 定</el-button>
        <el-button @click="cancelAddRole">取 消</el-button>
      </span>
    </el-dialog>

    <!--修改团队成员信息-->
    <el-dialog
        title="修改团队成员信息"
        :visible.sync="editDialogVisible"
        width="50%"
        :close-on-click-modal="false"
        @close="editTeamFormClose"
    >
      <el-form
          :model="editTeamForm"
          :rules="editTeamFormRules"
          ref="editTeamFormRef"
          label-width="100px"
          class="demo-ruleForm"
      >
        <!--从没有填写个人团队信息的管理员列表中选择，不可多选
      需要先排除已有项-->
        <el-form-item label="成员昵称" prop="managerName">
          <el-input v-model="editTeamForm.managerName" disabled/>
        </el-form-item>
        <!--type从上面选择的团队成员按照拥有角色映射，这里显示他的团队成分-->
        <el-form-item label="团队成分" prop="type">
          <el-input v-model="editTeamForm.typeName" disabled></el-input>
        </el-form-item>
        <el-form-item label="展示头像" prop="pic">
          <input type="file" @change="uploadPic"/>
          <img :src="showImg" alt="" :style="imgStyle"/>
        </el-form-item>
        <el-form-item label="简介" prop="introduce">
          <el-input v-model="editTeamForm.introduce"></el-input>
        </el-form-item>
        <el-form-item label="个人寄语" prop="message">
          <el-input v-model="editTeamForm.message"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editTeam">确 定</el-button>
        <el-button @click="editDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      imgStyle: 'width:100px',
      showImg: 'https://woniu-adopt.oss-cn-hangzhou.aliyuncs.com/adoptImages/',
      editDialogVisible: false,
      roleNames: [],
      teamTemp: '',
      pageNum: 1,
      pageSize: 12,
      teamList: [],
      roleList: [],
      managerList: [],
      roleIds: [], //存储选中的h角色ID
      total: 9,
      name: "",
      addDialogVisible: false,
      addTeamForm: {
        mid: '',
        type: 1,
        typeName:'',
        introduce:'',
        pic:'',
        message:''
      },
      editTeamForm: {},
      editTeamFormRules: {
        introduce: [
          {required: true, message: "请输入简介", trigger: "blur"},
        ],
        message: [
          {required: true, message: "请输入个人寄语", trigger: "blur"},
        ],
      },

      addTeamFormRules: {
        introduce: [
          {required: true, message: "请输入简介", trigger: "blur"},
        ],
        message: [
          {required: true, message: "请输入个人寄语", trigger: "blur"},
        ],
      }
    };
  },
  methods: {
    uploadPic(e) {
      let formData = new FormData();
      formData.append("file", e.target.files[0]);
      this.$axios({
        headers: {
          'Content-Type': "false",
        },
        method: 'post',
        url: "oss/upload",
        data: formData
      }).then(res => {
        if (res == 'fail') {
          alert("--对不起，添加失败--");
        } else {
          this.showImg = res.data;
          this.addTeamForm.pic = this.showImg.substring(this.showImg.lastIndexOf("/") + 1);
          this.editTeamForm.pic = this.addTeamForm.pic;
        }
      })
    },
    getRoleNames(list) {
      let info = '';
      if (list != null && list.length > 0) {
        for (let r of list) {
          info += r.name + ","
        }
      }
      return info.substring(0, info.length - 1);
    },
    async removeUserById(id) {
      this.$confirm('此操作将永久删除该本条信息, 是否继续?', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = '/manager/teamDelete/' + id;
        this.$axios.delete(url).then(res => {
          this.message(res);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    showEditDialog(row) {
      let temp = [];
      for (let r of row.roleList) {
        temp.push(r.id);
      }
      this.editTeamForm = row;
      this.editTeamForm.roleIds = temp;
      this.showImg=this.showImg+row.pic;
      this.editDialogVisible = true;
    },
    editTeamFormClose() {
      this.$refs.editTeamFormRef.resetFields();
      this.roleIds = [];
      this.editTeamForm.roleIds = "";
      this.showImg ='https://woniu-adopt.oss-cn-hangzhou.aliyuncs.com/adoptImages/';
      this.initTeam();
    },
    editTeam: function () {
      let url = "/manager/teamEdit";
      this.$refs.editTeamFormRef.validate(valid => {
        if (valid) {
          this.$axios.post(url, this.editTeamForm)
              .then(res => {
                this.message(res);
                this.editDialogVisible = false;
              })
        } else {
          console.log("验证失败");
          return false;
        }
      })

    },
    //添加管理员
    addTeam() {
      let url = "/manager/teamAdd";
      this.$refs.addTeamFormRef.validate(valid => {
        if (valid) {
          this.$axios.post(url, this.addTeamForm)
              .then(res => {
                this.message(res);
                this.$refs.addTeamFormRef.resetFields();
                this.addDialogVisible = false;
              })
        } else {
          console.log("验证失败");
        }
      })

    },
    //关闭添加团队信息的对话框
    addTeamFormClose() {
      this.addDialogVisible = false;
      this.$refs.addTeamFormRef.resetFields();
      this.roleIds = [];
    },
    //取消添加管理员
    cancelAddRole() {
      this.addDialogVisible = false;
      this.$refs.addTeamFormRef.resetFields();
      this.roleIds = [];
    },

    searchTeam() {
      this.initTeam();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.pageNum = 1;
      this.initTeam();
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.initTeam();
    },
    //初始化查询 用户信息
    initTeam() {
      let url = "/manager/teamList";
      this.$axios.get(url, {
        params: {
          now: this.pageNum,
          size: this.pageSize,
          name: this.name
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.teamList = res.data.data.list;
          this.pageSize = res.data.data.pageSize;
          this.pageNum = res.data.data.pageNum;
          this.total = res.data.data.total;
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg,
            duration: 1000
          })
        }
      })
    },
    //初始化查询 所有角色
    initRole() {
      let url = "/role/showAllRole";
      this.$axios.get(url).then(res => {
        if (res.data.code === 200) {
          this.roleList = res.data.data;
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg,
            duration: 1000
          })
        }
      })
    },
    initManagerList() {
      let url1 = "/manager/list";
      this.$axios.get(url1, {
        params: {
          //查询所有
          size: 100,
        }
      }).then(res => {
        if (res.data.code === 200) {
          res.data.data.list.forEach(item => {
            //先将所有mid查出存入,排除掉普通用户
            if (!(item.roles.length === 1 && item.roles[0].name === '普通用户')) {
              this.managerList.push(item);
            }
          });
          this.managerList.forEach((i, index) => {
            this.teamList.forEach(j => {
              if (i.id === j.mid) {
                //移除已有项[]
                delete this.managerList[index];
              }
            })
          })
          //清除delete留下的坑
          let temp = [];
          this.managerList.forEach(i => {
            if (i != null) {
              temp.push(i);
            }
          })
          this.managerList = temp;
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg,
            duration: 1000
          })
        }
      })
    },
    showTypeName(mid) {
      //查出所选所选管理员的团队成分
      //先获取所有的该账户的所有角色
      let url = 'manager/getRoleNamesByMid/' + mid;
      this.$axios.get(url).then(res => {
        if (res.data.code === 200) {
          this.roleNames = res.data.data;
          console.log(this.roleNames);
          //再根据角色映射团队成分
          let temp=[];
          console.log(this.roleNames)
          this.roleNames.forEach(roleName=>{
            if(roleName==='超级管理员'){
              temp.push(0);
            }else if(roleName==='普通管理员'){
              temp.push(1);
            }else if(roleName==='救助站工作人员'){
              temp.push(2);
            }else if (roleName==='志愿者'){
              temp.push(3);
            }else if(roleName==='特邀作家'){
              temp.push(4);
            }
          })
          //得到最小值
          console.log(temp)
          let min=temp[0];
          temp.forEach(i=>{
            min=i<min?i:min;
          })
          console.log(min)
          this.addTeamForm.type=min;
          if(min===0){
            this.addTeamForm.typeName='队长';
          }else if(min===1){
            this.addTeamForm.typeName='组员';
          }else if(min===2){
            this.addTeamForm.typeName='救助站工作人员';
          }else if(min===3){
            this.addTeamForm.typeName='志愿者';
          }else if(min===4){
            this.addTeamForm.typeName='特邀作家';
          }
        }
      });

    },
    message(res) {
      if (res.data.code === 200) {
        this.$message({
          type: 'success',
          message: res.data.msg,
          duration: 1000
        });
        this.initTeam();
      } else {
        this.$message({
          type: 'error',
          message: res.data.msg,
          duration: 1000
        })
      }
    }
  },
  created() {
    this.initTeam();
    this.initRole();
    this.initManagerList();
  }
};
</script>
<style lang="less" scoped>
</style>